package com.taotie.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taotie.entity.AiMessageModel;
import com.taotie.mapper.DishMapper;
import com.taotie.service.AiService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class AiServiceImpl implements AiService {

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @Value("${taotie.ai.client-id}")
    private String clientId;

    @Value("${taotie.ai.client-secret}")
    private String clientSecret;

    @Autowired
    private DishMapper dishMapper;

    @Override
    public String getMessage(List<AiMessageModel> message) {
        //获取AccessToken
        String accessToken = null;
        try {
            accessToken = getAccessToken();
        } catch (IOException e) {
            log.error("AccessToken获取失败");
            throw new RuntimeException(e);
        }
        //初始化map集合
        HashMap<String, List<AiMessageModel>> map = initHashMap(message);
        //发送请求并获取响应对象
        Response response = null;
        try {
            response = getResponse(map, accessToken);
        } catch (IOException e) {
            log.error("获取响应异常");
            throw new RuntimeException(e);
        }
        //解析响应
        JSONObject jsonObject = null;
        try {
            jsonObject = JSON.parseObject(response.body().string());
        } catch (IOException e) {
            log.error("解析响应异常");
            throw new RuntimeException(e);
        }
        //返回ai回答结果
        return jsonObject.getString("result");
    }

    @NotNull
    private HashMap<String, List<AiMessageModel>> initHashMap(List<AiMessageModel> message) {
        HashMap<String, List<AiMessageModel>> map = new HashMap<>();
        String string = JSON.toJSONString(dishMapper.dishAll());
        String format = String.format("现在你是本外卖平台的人工客服，本平台菜品数据库数据的json格式如下%s,当用户想你咨询问题时,要为用户提供解决方案,满足用户需求。", string);
        message.add(0,new AiMessageModel("user",format));
        message.add(1,new AiMessageModel("assistant","好的,我将扮演好外卖平台的人工客服来回答用户的问题,为用户提供解决方案,满足用户需求。"));
        map.put("messages", message);
        return map;
    }

    @NotNull
    private Response getResponse(HashMap<String, List<AiMessageModel>> message, String accessToken) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(message));
        Request request = new Request.Builder()
                .url(String.format(
                        "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=%s",
                        accessToken
                ))
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        return HTTP_CLIENT.newCall(request).execute();
    }

    private String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url(String.format(
                        "https://aip.baidubce.com/oauth/2.0/token?client_id=%s&client_secret=%s&grant_type=client_credentials",
                        clientId,
                        clientSecret
                ))
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        //解析响应
        JSONObject jsonObject = JSONArray.parseObject(response.body().string());
        //获取AccessToken并返回
        return jsonObject.getString("access_token");
    }

}
